package com.plugins.http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpStatus;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.iclient.dao.ext.PageModel;

public class HttpSinaUtil {
	
	private static final Pattern r = Pattern.compile("粉丝(\\d*)人");
	
	/**
	 * 查找用户
	 */
	public static PageModel<Map<String, Object>> searchUser(String keyword, Integer page) throws UnsupportedEncodingException{
		StringBuffer sb = new StringBuffer("http://weibo.cn/search/user/?vt=4");
		sb.append("&keyword=").append(URLEncoder.encode(keyword, "utf-8"));
		if(page != null && page > 0)
			sb.append("&page="+page);
		CloseableHttpClient httpClient = HttpUtils.httpClient;
		HttpClientContext httpContext = HttpClientContext.create();
		httpContext.setCookieStore(HttpUtils.getCookie());
		HttpGet httpGet = new HttpGet(sb.toString());
		httpGet.addHeader("User-Agent", HttpUserAgent.getUserAgent());
		httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
		httpGet.addHeader("Accept-Encoding", "gzip, deflate");
		RequestConfig config = RequestConfig.custom()
				//.setProxy(new HttpHost("127.0.0.1", 8888))
				.setCookieSpec(CookieSpecs.STANDARD)
				.setRedirectsEnabled(true)
				.build();
		httpGet.setConfig(config);
		try{
			CloseableHttpResponse httpResponse = httpClient.execute(httpGet, httpContext);
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				String content = EntityUtils.toString(httpResponse.getEntity());
				System.out.println(content);
				Document document = Jsoup.parse(content);
				PageModel<Map<String, Object>> pageModel = new PageModel<>();
				String total = document.getElementsByClass("cmt").first().text().replace("共", "").replace("条", "");
				pageModel.setTotal(Integer.valueOf(total));
				pageModel.setPage(page);
				pageModel.setPageSize(10);
				Elements tables = document.getElementsByTag("tr");
				List<Map<String, Object>> list = new ArrayList<>();
				for(int i=0; i<tables.size(); i++){
					Element element = tables.get(i);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("mainpage", "http://weibo.cn"+element.select("a").first().attr("href"));
					map.put("avatar", element.select("img").first().attr("src"));
					map.put("nickname", element.select("a").get(1).text());
					map.put("addUrl", "http://weibo.cn" + element.select("a").last().attr("href"));
					list.add(map);
				}
				pageModel.setRows(list);
				return pageModel;
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			httpGet.releaseConnection();
		}
		return null;
	}
	
	/**
	 * 获取用户首页信息
	 */
	public static Map<String, String> getUserIndex(String mainpage){
		CloseableHttpClient httpClient = HttpUtils.httpClient;
		HttpClientContext httpContext = HttpClientContext.create();
		httpContext.setCookieStore(HttpUtils.getCookie());
		HttpGet httpGet = new HttpGet(mainpage);
		httpGet.addHeader("User-Agent", HttpUserAgent.getUserAgent());
		httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
		httpGet.addHeader("Accept-Encoding", "gzip, deflate");
		RequestConfig config = RequestConfig.custom()
				//.setProxy(new HttpHost("127.0.0.1", 8888))
				.setCookieSpec(CookieSpecs.STANDARD)
				.setRedirectsEnabled(false)
				.build();
		httpGet.setConfig(config);
		try{
			CloseableHttpResponse httpResponse = httpClient.execute(httpGet, httpContext);
			String content = EntityUtils.toString(httpResponse.getEntity());
			System.out.println(content);
			Document document = Jsoup.parse(content);
			Elements eles = document.select("div.tip2 > a");
			Element e = eles.get(1);
			Map<String, String> map = new HashMap<>();
			map.put("url", e.attr("href"));
			map.put("text", e.text());
			return map;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			httpGet.releaseConnection();
		}
		return null;
	}
	
	/**
	 * 
	 * 获取用户的粉丝
	 */
	public static List<Map<String, Object>> getUserFans(String url){
		CloseableHttpClient httpClient = HttpUtils.httpClient;
		HttpClientContext httpContext = HttpClientContext.create();
		httpContext.setCookieStore(HttpUtils.getCookie());
		HttpGet httpGet = new HttpGet(url);
		httpGet.addHeader("User-Agent", HttpUserAgent.getUserAgent());
		httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
		httpGet.addHeader("Accept-Encoding", "gzip, deflate");
		RequestConfig config = RequestConfig.custom()
				//.setProxy(new HttpHost("127.0.0.1", 8888))
				.setCookieSpec(CookieSpecs.STANDARD)
				.setRedirectsEnabled(false)
				.build();
		httpGet.setConfig(config);
		try{
			CloseableHttpResponse httpResponse = httpClient.execute(httpGet, httpContext);
			String content = EntityUtils.toString(httpResponse.getEntity());
			System.out.println(content);
			Document document = Jsoup.parse(content);
			Elements tables = document.getElementsByTag("tr");
			List<Map<String, Object>> list = new ArrayList<>();
			for(int i=0; i<tables.size(); i++){
				Element element = tables.get(i);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("mainpage", element.select("a").first().attr("href"));
				map.put("avatar", element.select("img").first().attr("src"));
				map.put("nickname", element.select("a").get(1).text());
				map.put("addurl", element.select("a").last().attr("href"));
				Matcher m = r.matcher(element.text());
				if(m.find()){
					map.put("fans", Integer.valueOf(m.group(1)));
				}
				String addUrl = (String) map.get("addurl");
				//http://weibo.cn/attention/add?uid=6031376739&rl=1&vt=4&st=62b4b8
				if(addUrl.contains("attention")){
					addUrl = addUrl.substring(addUrl.indexOf("?")+1, addUrl.indexOf("&"));
					map.put("uid", addUrl.replace("uid=", ""));
				}
				System.out.println(map);
				list.add(map);
			}
			return list;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			httpGet.releaseConnection();
		}
		return null;
	}
	
	
}
